import OpenAI from "openai";

export default defineBackground(() => {
  console.log("AI问答助手后台脚本已启动", { id: browser.runtime.id });

  // 存储活动的请求控制器
  const activeRequests = new Map();

  // 监听来自内容脚本的消息
  browser.runtime.onMessage.addListener((message, sender, sendResponse) => {
    console.log("后台收到消息:", message);

    if (message.type === "alibabaApiRequest") {
      console.log("收到阿里云API请求:", message.requestId);

      // 立即发送确认消息
      try {
        browser.tabs.sendMessage(sender.tab.id, {
          type: "alibabaApiRequestReceived",
          requestId: message.requestId,
          timestamp: Date.now(),
        });
        console.log("已发送确认消息:", message.requestId);
      } catch (error) {
        console.error("发送确认消息失败:", error);
      }

      // 处理API请求
      handleAlibabaApiRequest(message, sender);

      // 返回true以支持异步响应
      return true;
    }

    // 处理停止生成请求
    else if (message.type === "stopGeneration") {
      const requestId = message.requestId;
      console.log(
        "收到停止生成请求:",
        requestId,
        "活动请求数:",
        activeRequests.size
      );
      console.log("活动请求列表:", Array.from(activeRequests.keys()));

      const controller = activeRequests.get(requestId);
      if (controller) {
        console.log("找到对应的控制器，执行中止操作");

        // 确保在try/catch块中执行中止操作
        try {
          // 中止请求
          controller.abort();
          console.log("控制器已中止, 新状态:", controller.signal.aborted);

          // 立即发送停止确认消息给内容脚本
          try {
            // 发送停止确认消息
            browser.tabs.sendMessage(sender.tab.id, {
              type: "alibabaApiStopped",
              requestId: requestId,
              partialResponse: controller.partialResponse || "",
            });
            console.log("已发送停止确认消息");
          } catch (sendErr) {
            console.error("发送停止确认消息失败:", sendErr);
          }

          // 从活动请求中移除
          activeRequests.delete(requestId);
          console.log("请求已从活动列表中移除:", requestId);

          // 返回true表示我们将异步处理这个请求
          return true;
        } catch (err) {
          console.error("执行中止操作失败:", err);
          // 通知内容脚本中止失败
          browser.tabs.sendMessage(sender.tab.id, {
            type: "alibabaApiError",
            requestId: requestId,
            error: "无法停止生成: " + err.message,
          });
        }
      } else {
        console.log("未找到请求ID对应的控制器:", requestId);
        // 通知内容脚本未找到请求
        browser.tabs.sendMessage(sender.tab.id, {
          type: "alibabaApiError",
          requestId: requestId,
          error: "未找到对应的请求",
        });
      }
    }
  });
  // 处理阿里云API请求的函数
  async function handleAlibabaApiRequest(message, sender) {
    const { requestId, apiUrl, apiKey, apiVersion, messages } = message;

    try {
      // 创建中止控制器
      const controller = new AbortController();
      controller.partialResponse = "";

      // 存储到活动请求
      activeRequests.set(requestId, controller);

      console.log(
        "准备调用API:",
        "请求ID:",
        requestId,
        "控制器状态:",
        controller.signal.aborted
      );

      // 将请求包装在 Promise.race 中，以便与自己创建的可中断 Promise 竞争
      let isCancelled = false;
      let resolveCancel;

      const cancelPromise = new Promise((resolve) => {
        resolveCancel = () => {
          isCancelled = true;
          resolve("cancelled");
        };
      });

      // 监听 abort 事件
      controller.signal.addEventListener("abort", () => {
        console.log("Abort 事件被触发，执行取消操作:", requestId);
        resolveCancel();
      });

      // 执行 API 调用的 Promise
      const apiPromise = (async () => {
        const openai = new OpenAI({
          // 若没有配置环境变量，请用百炼API Key将下行替换为：apiKey: "sk-xxx",
          apiKey: message.apiKey,
          baseURL: message.apiUrl,
          dangerouslyAllowBrowser: true,
        });

        console.log("openai", openai, message);

        const completion = await openai.chat.completions.create(
          {
            model: message.apiVersion,
            messages: message.messages,
            stream: true,
            stream_options: {
              include_usage: true,
            },
          },
          { signal: controller.signal }
        );

        let fullContent = "";
        console.log("流式输出内容开始，请求ID:", requestId);

        for await (const chunk of completion) {
          // 检查是否被取消
          if (isCancelled) {
            console.log("检测到取消标志，中断流式处理:", requestId);
            break;
          }

          // 如果stream_options.include_usage为true，则最后一个chunk的choices字段为空数组，需要跳过
          if (Array.isArray(chunk.choices) && chunk.choices.length > 0) {
            const textChunk = chunk.choices[0].delta.content;
            if (textChunk) {
              // 确保内容不是undefined或null
              fullContent = fullContent + textChunk;
              controller.partialResponse = fullContent; // 保存部分响应

              // 发送流式响应块回内容脚本
              try {
                await browser.tabs.sendMessage(sender.tab.id, {
                  type: "alibabaApiStreamChunk",
                  requestId: requestId,
                  chunk: textChunk,
                });
              } catch (err) {
                console.error("发送流式数据块失败:", err);
                break;
              }
            }
          }
        }

        // 如果没有被取消，发送完整响应
        if (!isCancelled) {
          console.log("流式响应完成，发送完整响应:", requestId);
          await browser.tabs.sendMessage(sender.tab.id, {
            type: "alibabaApiResponse",
            requestId: requestId,
            fullResponse: fullContent,
          });
        }

        return fullContent;
      })();

      // 使用 Promise.race 在 API 调用和取消之间竞争
      const result = await Promise.race([apiPromise, cancelPromise]);

      // 如果是因为取消而结束的
      if (result === "cancelled") {
        console.log("成功取消了请求，发送部分响应:", requestId);
        await browser.tabs.sendMessage(sender.tab.id, {
          type: "alibabaApiStopped",
          requestId: requestId,
          partialResponse: controller.partialResponse || "",
        });
      }
    } catch (error) {
      console.error("处理API请求出错:", error);
      // 发送错误回内容脚本
      browser.tabs.sendMessage(sender.tab.id, {
        type: "alibabaApiError",
        requestId: message.requestId,
        error: error.message,
      });
    } finally {
      // 清理
      activeRequests.delete(requestId);
      console.log("请求处理完成，从活动请求中移除:", requestId);
    }
  }
});
